/*
* 描述：SSY活动，总部发起新活动，添加活动基本信息、添加资源分配信息、活动参与者、添加OT竞品信息
* 对应需求文档：3.3.2
* 对应UI Design:W-T-SSY-1
* 负责人 付海莎
*/
public with sharing class InitActivityForNTMKTListController {  
     
   public Activity_Information__c ActivityInit{get;set;} //初始化活动对象
   public Resource_Allocation__c ResourceObj{get;set;}//初始化资源分配
   
   public List<ActivityResourceEntry> ResourceEntryList{get;set;}//资源分配集合 
   public List<ActivityParticipatorEntry> ParticipatorAreaEntryList{get;set;}//OT参与列表area集合  
   public List<ActivityParticipatorEntry> ParticipatorAreaKAList{get;set;}//KA参与列表，绑定到页面
    public List<ActivityCompetitionBrandEntry> CompetitionBrandList{get;set;}//竞品信息
    
   public CommonAttribute PlaceAttribute{get;set;}//地域信息;
   public CommonMethod getMethod;//公共方法
   public Boolean IsNc{get;set;}//参与列表，是否是NC店过滤条件
   public String RegionSelectedValue{get;set;}//选中的区域值
    public String SubRegionSelectedValue{get;set;}//选中片区的值
    public String AreaSelectedValue{get;set;}//区域选择的值
    
    public List<Participator_Detail_Area__c> participatorDetailArea;//参与列表明细Area ASM
    public  List<Participator_Detail_Outlet__c> outletDetail{get;set;}//保存参与列表明细outlet
    public Map<String,ActivityParticipatorEntry> mapParticipatorAreaList;  //保存OT参与列表
    public Map<String,ActivityParticipatorEntry >mapParticipatorAreaKAList;//保存KA参与列表
    public Map<string,Participator_Detail_Outlet__c> participatorDetialOutletMapList;
 
    public Boolean IsKADisplay{get;set;}//是否显示KA的部分
    public Boolean IsOTDisplay{get;set;}//是否显示OT的部分
    public Boolean IsAdjustDisplay{get;set;}//调整KA资源按钮是否显示
    public Boolean IsSelectedAllCompetition{get;set;}//竟品费用全选
    public Boolean CheckParticipatorAll{get;set;}//参与者列表全选
    
    public Boolean IsDisplayCancelActivity{get;set;}//取消按钮是否可见
    
  public List<SelectOption> GetActivityTypeItem//活动类型，KA、OT   
   {
       get 
       {
            List<SelectOption> option=new List<SelectOption>();
            option.add(new SelectOption('OT','OT'));
            option.add(new SelectOption('KA','KA'));
            return option;
       }
   }
   public String getTypeKAOrOT{get;set;}//获得用户选择的KA、OT
   public String Set1ButtonText{get;set;}//第一步骤的按钮显示文本
   public Boolean IsEnableActionButton{get;set;}//按钮是否可用
  //获得记录ID
   public String RecordId
   {
       get
       {
           if(System.currentPageReference().getParameters().get('id')!=NULL)
               return System.currentPageReference().getParameters().get('id').substring(0,15);  
           else
               return null;
       }
       set;
   }
   //保存参与者门店ID
   public Set<Id> AllParticipatorOutletId
   {
      get;set;
   }
  //获取Record Type Id
    public String RecordTypeId
    {
        get{        
                return System.currentPageReference().getParameters().get('RecordType');     
           }  
        set;
    }
    //用户信息
  public User u{
    get{
   return getMethod.getUserInfo();
    }
}   
    //构造函数,初始化所有必要的信息
     public InitActivityForNTMKTListController(ApexPages.StandardController controller)
     {
             getMethod=new CommonMethod();
             Set1ButtonText='保存进入下一步';
             IsEnableActionButton=true;
            //初始化参与者和参与者明细列表 
             if(outletDetail==NULL)
                 outletDetail=new List<Participator_Detail_Outlet__c>();
             if( participatorDetailArea==NULL)
                  participatorDetailArea=new List<Participator_Detail_Area__c>();    
                 
             AllParticipatorOutletId=new Set<Id>();
            IsNc=true;
            ActivityInit=new Activity_Information__c();
            ResourceObj=new Resource_Allocation__c();
            PlaceAttribute=new CommonAttribute();
            ResourceEntryList=new List<ActivityResourceEntry>();
            ActivityInit.RecordTypeId=RecordTypeId;
           ActivityInit.Activity_Stage__c='草稿';
           ActivityInit.Activity_Type_State__c='正常';
           if(getTypeKAOrOT==NULL)
               getTypeKAOrOT='OT';
           IsKADisplay=false;
           IsOTDisplay=true;
           IsAdjustDisplay=false;
            if(RecordId!=NULL)//更新状态
            {
                 ActivityInit=[Select Id,Name,OwnerId,RecordTypeId, ASMConfirmDate__c, ASMFinishDate__c, Activity_End_Date__c,IsNcOrNotForOT__c,IsNcOrNotForKA__c,
                                  Activity_Notice__c, Activity_Stage__c, Activity_Start_Date__c, Activity_Type_State__c, Activity_Type__c, 
                                  KAMConfirmDate__c, KAMFinishAdjustDate__c, NTMKTFinishApproveDate__c, RSMFinishApproveDate__c, 
                                  RTMFinishApproveDate__c, SRTMFinishApproveDate__c, SRTMFinishDate__c,Serial_Number__c
                                   FROM Activity_Information__c  where id=:RecordId];
                                   
                   //取消按钮是否显示
                Date StartDT=ActivityInit.Activity_Start_Date__c;                   
                if(Date.today()>= StartDT.addDays(-20))//开始活动前21天不可以调时间
                      IsDisplayCancelActivity=false;
                else
                     IsDisplayCancelActivity=true;
                                   
                 if(u.id!=ActivityInit.OwnerId || ActivityInit.Activity_Stage__c=='总部已发起活动' || ActivityInit.Activity_Stage__c=='活动已取消')
                 {
                     Set1ButtonText='下一步';
                     IsEnableActionButton=false;
                     IsDisplayCancelActivity=false;
                 }                  
                 //初始化资源分配信息
             if(ResourceEntryList==NULL)
                  ResourceEntryList=new List<ActivityResourceEntry>();
             for(Resource_Allocation__c res:[Select Activity_Information_Name__c, KA_Allocation_Number__c, OT_Allocation_Number__c, 
                                             Product_Code__c, Product_Name__c, Resource_Allocation_Number__c, Resource_Type__c,ETOrFGCode__c, 
                                             Allocation_Sum_Total__c FROM Resource_Allocation__c where Activity_Information_Name__c=:RecordId])
                  {
                      Resource_Allocation__c resNewInstance=new Resource_Allocation__c();
                      resNewInstance.Activity_Information_Name__c=RecordId;
                      resNewInstance.KA_Allocation_Number__c=res.KA_Allocation_Number__c;
                      resNewInstance.OT_Allocation_Number__c=res.OT_Allocation_Number__c;
                      resNewInstance.Product_Name__c=res.Product_Name__c;
                      resNewInstance.ETOrFGCode__c=res.Product_Code__c;
                      ResourceEntryList.add(new ActivityResourceEntry(false,resNewInstance,Integer.valueOf(res.Allocation_Sum_Total__c)));    
                  }
           //加载竟品信息
           if(CompetitionBrandList==NULL)
                 CompetitionBrandList=new List<ActivityCompetitionBrandEntry>();
            for(Activity_Competition_Brand_Information__c acb:[Select  Name, Activity_Information__c, Type__c, Competition_Cost_Source__c, Competition_Cost_Type__c,
                                                 Competition_Promotion_Type__c FROM Activity_Competition_Brand_Information__c 
                                                 where Activity_Information__c=:RecordId and Type__c='OT'])
            {
                CompetitionBrandList.add(new ActivityCompetitionBrandEntry(false,acb));
            }
            
             if(ParticipatorAreaEntryList==NULL)
                 ParticipatorAreaEntryList=new  List<ActivityParticipatorEntry>();//OT
             if(mapParticipatorAreaList==NULL)
                  mapParticipatorAreaList=new Map<String,ActivityParticipatorEntry >();//OT Map 
             if(ParticipatorAreaKAList==NULL)
                 ParticipatorAreaKAList=new  List<ActivityParticipatorEntry>();//KA
             if(mapParticipatorAreaKAList==NULL)
                 mapParticipatorAreaKAList=new Map<String,ActivityParticipatorEntry>();//KA Map
            
             //初始化参与列表(area)
             for(ParticipatorArea__c entry: [Select Activity_Name__c, KA_Status__c, KA__c, Type__c, OutletType__c, Channel__c, 
                                                                                   Sub_region__c, Region__c, Outlet_Sum_Total__c, Area__c,IsNCOrNot__c 
                                                                                   FROM ParticipatorArea__c where Activity_Name__c=: RecordId])
              {
                      if(entry.Type__c=='OT')
                      {
                          
                        //   String key=area.Area__c+area.OutletType__c+area.Channel__c;   
                          String key=entry.Region__c+entry.Sub_region__c+entry.Area__c+entry.KA__c+entry.OutletType__c+entry.Channel__c;     
                          mapParticipatorAreaList.put(key,new ActivityParticipatorEntry(false,entry));
                          ParticipatorAreaEntryList.add(new ActivityParticipatorEntry(false,entry));     
                      }
                      if(entry.Type__c=='KA')
                      {
                        //  String key=area.Area__c+area.OutletType__c+area.Channel__c+area.KA__c;
                           String key=entry.Region__c+entry.Sub_region__c+entry.Area__c+entry.KA__c+entry.OutletType__c+entry.Channel__c;     
                          mapParticipatorAreaKAList.put(key,new ActivityParticipatorEntry(false,entry));
                          ParticipatorAreaKAList.add(new ActivityParticipatorEntry(false,entry));     
                      }                                                         
               }
              
            }
            
           
     }
  
     //添加资源
      public PageReference AddResource()
      {
          if(ResourceEntryList.size()>=5)
              return null;
          if(ResourceObj.Product_Name__c != NULL)
          {
              for(ActivityResourceEntry entry:ResourceEntryList)
              {
                 if( entry.res.Product_Name__c==ResourceObj.Product_Name__c)
                     return null;
              }
            //查找产品Code
            Product2 pro=[select SKU_Code__c from Product2 where id=:ResourceObj.Product_Name__c limit 1];
            ResourceObj.ETOrFGCode__c=pro.SKU_Code__c;
            
            ResourceEntryList.add(new ActivityResourceEntry(false,ResourceObj));
            ResourceObj=NULL;
            ResourceObj=new Resource_Allocation__c(); 
            integer i=ResourceEntryList.size()-1;
            ResourceEntryList[i].Res.KA_Allocation_Number__c=0;
             ResourceEntryList[i].Res.OT_Allocation_Number__c=0;
         }
        return null;
      }
      //删除资源
      public PageReference DelResource()
      {
        for(Integer i=0;i<ResourceEntryList.size();i++)
        {
            ActivityResourceEntry activityRes=ResourceEntryList[i];
            if(activityRes.isCheck)
            {
                ResourceEntryList.remove(i);
                i--;
            }
        }
        return null;
      }
    
      //重置所有
      public PageReference ResetALLData()
      {
         for(ActivityResourceEntry r:ResourceEntryList){
             r.Res.KA_Allocation_Number__c=0;
              r.Res.OT_Allocation_Number__c=0;
              r.TotalResourceNumber=0;
          }
         return null;
      }
      //条件过滤
      public String Filter(String outletType,String channel)
      {
            String filter='';
          if(outletType!='' && outletType!=NULL)
          {
                            filter+=' and ';
                            filter+='Outlet_Type__c=\''+outletType+'\'';
           }
             if(channel!='' && channel!=NULL)
              {
                              filter+=' and ';
                             filter+='Channel__c=\''+channel+'\'';
              }
          if(IsNc==true)//是否是NC店
              filter+=' and With_NC_or_not__c ='+IsNc;
              
              return filter;
      } 
      //添加参与者
     
    public PageReference AddParticipator()
    {
       if((PlaceAttribute.RegionSelectedValue==NULL || PlaceAttribute.RegionSelectedValue=='0') && 
           (PlaceAttribute.SubRegionSelectedValue==NULL || PlaceAttribute.SubRegionSelectedValue=='0') && 
           (PlaceAttribute.AreaSelectedValue==NULL || PlaceAttribute.AreaSelectedValue=='0'))
                throw new CustomException ('请选择一个地域');     
                    
        if(getTypeKAOrOT=='KA')
        {         
           if( mapParticipatorAreaKAList==null)
               mapParticipatorAreaKAList=new Map<String,ActivityParticipatorEntry >();
           if(ParticipatorAreaKAList==NULL)
                ParticipatorAreaKAList=new List<ActivityParticipatorEntry>();
          getMethod.AddParticipators('KA',mapParticipatorAreaKAList,ParticipatorAreaKAList,PlaceAttribute,ActivityInit.IsNcOrNotForKA__c,ActivityInit);            
        }                
         if(getTypeKAOrOT=='OT')
         {            
                  if( mapParticipatorAreaList==NULL)
                      mapParticipatorAreaList=new Map<String,ActivityParticipatorEntry >();                      
                  getMethod.AddParticipators('OT',mapParticipatorAreaList,ParticipatorAreaEntryList,PlaceAttribute,ActivityInit.IsNcOrNotForOT__c,ActivityInit);                 
        }
           
        return null;
    }
    //添加参与者
     /*
    public PageReference AddParticipator()
    {
         outletDetail=new List<Participator_Detail_Outlet__c>();
         for(Participator_Detail_Outlet__c par:[select Outlet_Name__c from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:RecordId])
        {
            AllParticipatorOutletId.add(par.Outlet_Name__c);
        }
            if(PlaceAttribute.AreaSelectedValue==NULL || PlaceAttribute.AreaSelectedValue=='0')
                throw new CustomException ('请选择一个区域');
              
        if(getTypeKAOrOT=='KA')
        {
             if(PlaceAttribute.KASelectedValue==NULL || PlaceAttribute.KASelectedValue=='0')
             throw new CustomException ('请选择一个KA');
         
           if( mapParticipatorAreaKAList==null)
               mapParticipatorAreaKAList=new Map<String,ActivityParticipatorEntry >();
           if(ParticipatorAreaKAList==NULL)
                ParticipatorAreaKAList=new List<ActivityParticipatorEntry>();
               
                  String sql='select id,OwnerId from Account where Active_Status__c=\'正常营业\' and  OutletArea__c=\''+PlaceAttribute.AreaSelectedValue+'\' and Chain_Customer__c=\''+PlaceAttribute.KASelectedValue+'\' '+Filter(PlaceAttribute.OutletTypeSelectedValue,PlaceAttribute.ChannelSelectedValue);
                  List<Account> ListCountLastActual=new  List<Account>();
                  ListCountLastActual=Database.Query(sql);  
                 String key=PlaceAttribute.AreaSelectedValue+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue+PlaceAttribute.KASelectedValue;
                   
                   if(!mapParticipatorAreaKAList.containsKey(key))
                    {
                         ParticipatorArea__c par=new ParticipatorArea__c(Activity_Name__c=RecordId,
                                                                                  Region__c=PlaceAttribute.RegionSelectedValue,
                                                                                  Sub_region__c=PlaceAttribute.SubRegionSelectedValue,
                                                                                  Area__c=PlaceAttribute.AreaSelectedValue,
                                                                                  OutletType__c=PlaceAttribute.OutletTypeSelectedValue,
                                                                                  Channel__c=PlaceAttribute.ChannelSelectedValue,
                                                                                  KA__c=PlaceAttribute.KASelectedValue,
                                                                                  Type__c='KA',
                                                                                  IsNCOrNot__c=IsNc,
                                                                                  Outlet_Sum_Total__c=ListCountLastActual.size());
                                                                                  
                           insert par;                       
                    
                           for(Account acc:ListCountLastActual)
                            {
                                 if(!AllParticipatorOutletId.contains(acc.Id))
                                {
                                    outletDetail.add(new Participator_Detail_Outlet__c(Outlet_Name__c=acc.id,
                                                                                                                    Participator_Area__c=par.Id,
                                                                                                                   Outlet_Type__c='正常营业',
                                                                                                                   OutletResourceType__c='KA',
                                                                                                                   OwnerId=acc.OwnerId));
                                    AllParticipatorOutletId.add(acc.id);                                                                                        
                                }
                            }
                          insert  outletDetail;
                          
                         ActivityParticipatorEntry entry=new ActivityParticipatorEntry (false,par);                                            
                        mapParticipatorAreaKAList.put(key,entry);   
                       
                        if(mapParticipatorAreaKAList.size()>0)
                        {
                               ParticipatorAreaKAList.clear();
                             for(ActivityParticipatorEntry  ee:mapParticipatorAreaKAList.values())
                             {
                                    ParticipatorAreaKAList.add(new ActivityParticipatorEntry(false,ee.ParArea));
                             }
                        }
                    }
        }                
         if(getTypeKAOrOT=='OT')
         {
                   String key=PlaceAttribute.AreaSelectedValue+PlaceAttribute.OutletTypeSelectedValue+PlaceAttribute.ChannelSelectedValue;
                  if( mapParticipatorAreaList==NULL)
                      mapParticipatorAreaList=new Map<String,ActivityParticipatorEntry >();
                    if(!mapParticipatorAreaList.containsKey(key))
                    {
                        //查询门店
                          String sql='select id,OwnerId from Account where Active_Status__c=\'正常营业\' and Chain_Customer__c=NULL  and  OutletArea__c=\''+PlaceAttribute.AreaSelectedValue+'\' '+Filter(PlaceAttribute.OutletTypeSelectedValue,PlaceAttribute.ChannelSelectedValue);
                          List<Account> ListCountLastActual=new  List<Account>();
                           ListCountLastActual=Database.Query(sql);                                          
                           
                       ParticipatorArea__c par= new ParticipatorArea__c(Activity_Name__c=RecordId,
                                                                       Region__c=PlaceAttribute.RegionSelectedValue,
                                                                      Sub_region__c=PlaceAttribute.SubRegionSelectedValue,
                                                                      Area__c=PlaceAttribute.AreaSelectedValue,
                                                                      OutletType__c=PlaceAttribute.OutletTypeSelectedValue,
                                                                      Channel__c=PlaceAttribute.ChannelSelectedValue,
                                                                      Outlet_Sum_Total__c=ListCountLastActual.size(),
                                                                       IsNCOrNot__c=IsNc,
                                                                      Type__c='OT');
                                                                      
                           insert par;//保存参与列表明细Area
                          for(Account acc:ListCountLastActual)
                            {
                                if(!AllParticipatorOutletId.contains(acc.Id))
                                {
                                       outletDetail.add(new Participator_Detail_Outlet__c(Outlet_Name__c=acc.id,
                                                                                                                                   Participator_Area__c=par.id,
                                                                                                                                  Outlet_Type__c='正常营业',
                                                                                                                                  OutletResourceType__c='OT',
                                                                                                                                  OwnerId=acc.OwnerId));
                                        AllParticipatorOutletId.add(acc.id);
                                 }
                            }
                          insert  outletDetail;//保存参与列表明细Outlet                                        
                        ActivityParticipatorEntry entry=new ActivityParticipatorEntry (false,par);
                        mapParticipatorAreaList.put(key,entry); 
                        ParticipatorAreaEntryList.add(entry);
                    //   if(mapParticipatorAreaList.size()>0)
                        {
                               ParticipatorAreaEntryList.clear();
                             for(ActivityParticipatorEntry  ee:mapParticipatorAreaList.values())
                             {
                                    ParticipatorAreaEntryList.add(new ActivityParticipatorEntry(false,ee.ParArea));
                             }
                        }//
                    }
        }
    
         PlaceAttribute.RegionSelectedValue='';
         PlaceAttribute.SubRegionSelectedValue='';
         PlaceAttribute.AreaSelectedValue='';
         PlaceAttribute.OutletTypeSelectedValue='';
         PlaceAttribute.ChannelSelectedValue='';
          PlaceAttribute.KASelectedValue='';
          
        return null;
    }*/
    //删除参与者
     public PageReference DelParticipator()
     {
          if(getTypeKAOrOT=='OT')
          {
             for(Integer i=0;i<ParticipatorAreaEntryList.size();i++)
             {
                 ActivityParticipatorEntry entry=ParticipatorAreaEntryList[i];
                 if(entry.IsCheck)
                 {
                     //String key=entry.ParArea.Area__c+entry.ParArea.OutletType__c+entry.ParArea.Channel__c;     
                     String key=entry.ParArea.Region__c+entry.ParArea.Sub_region__c+entry.ParArea.Area__c+entry.ParArea.KA__c+entry.ParArea.OutletType__c+entry.ParArea.Channel__c;
                      mapParticipatorAreaList.remove(key);   
                   
                     ParticipatorAreaEntryList.remove(i);
                     if(entry.ParArea.Outlet_Sum_Total__c>0){
                       delete [select id from Participator_Detail_Outlet__c where Participator_Area__c=:entry.ParArea.Id];
                       delete [select id from ParticipatorArea__c where Id=:entry.ParArea.Id];
                     }
                     i--;
                 }
             }
         }
         else
         {
            
              for(Integer i=0;i<ParticipatorAreaKAList.size();i++)//KA
             {
                 ActivityParticipatorEntry entry=ParticipatorAreaKAList[i];
                 if(entry.IsCheck)
                 {
                   //  String key=entry.ParArea.Area__c+entry.ParArea.OutletType__c+entry.ParArea.Channel__c+entry.ParArea.KA__c;
                    String key=entry.ParArea.Region__c+entry.ParArea.Sub_region__c+entry.ParArea.Area__c+entry.ParArea.KA__c+entry.ParArea.OutletType__c+entry.ParArea.Channel__c;
                     mapParticipatorAreaKAList.remove(key);
                        // System.assert(false,mapParticipatorAreaKAList);
                     ParticipatorAreaKAList.remove(i);
                     if(entry.ParArea.Outlet_Sum_Total__c>0){
                       delete [select id from Participator_Detail_Outlet__c where Participator_Area__c=:entry.ParArea.Id];
                       delete [select id from ParticipatorArea__c where Id=:entry.ParArea.Id];
                     }
                     i--;
                 }
             }
         }
         return null;
     }
     //活动参与
     public PageReference onCheckByActivityType()
     {
         if(getTypeKAOrOT=='OT')
         {
              IsKADisplay=false;
              IsOTDisplay=true;
         }
         else  if(getTypeKAOrOT=='KA')
         {
              IsKADisplay=true;
              IsOTDisplay=false;
         }
         return null;
     }
     //添加竞品信息
     public PageReference addCompetitionBrandAction()
     {
         if(CompetitionBrandList==NULL)
             CompetitionBrandList=new  List<ActivityCompetitionBrandEntry>();
             try
             {
                 if(CompetitionBrandList.size()>=5)
                     throw new CustomException ('竞品类型不能超过5种');
                 if(PlaceAttribute.SSYPromotionTypeSelectedValue=='' || PlaceAttribute.SSYPromotionTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竟品促销形式');
                 if(PlaceAttribute.SSYOTCostTypeSelectedValue=='' || PlaceAttribute.SSYOTCostTypeSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用形式');
                  if(PlaceAttribute.CostSourceSelectedValue=='' || PlaceAttribute.CostSourceSelectedValue==NULL)
                      throw new CustomException ('请选择竞品费用来源');
                      
                   for(ActivityCompetitionBrandEntry entry:CompetitionBrandList)   
                   {
                       if(entry.ActivityCompetitionMsg.Competition_Cost_Source__c==PlaceAttribute.CostSourceSelectedValue &&
                          entry.ActivityCompetitionMsg.Competition_Cost_Type__c== PlaceAttribute.SSYOTCostTypeSelectedValue &&
                          entry.ActivityCompetitionMsg.Competition_Promotion_Type__c==PlaceAttribute.SSYPromotionTypeSelectedValue)
                              return null;
                   }
                    Activity_Competition_Brand_Information__c activity=new Activity_Competition_Brand_Information__c(Activity_Information__c=RecordId,
                                                                                                  Competition_Cost_Source__c=PlaceAttribute.CostSourceSelectedValue,
                                                                                                  Competition_Cost_Type__c=PlaceAttribute.SSYOTCostTypeSelectedValue,
                                                                                                   Competition_Promotion_Type__c=PlaceAttribute.SSYPromotionTypeSelectedValue,
                                                                                                    Type__c='OT' );
                   CompetitionBrandList.add(new ActivityCompetitionBrandEntry(false,activity));
                   insert activity;
             }
             catch(Exception ex)
             {
                  ApexPages.addMessages(ex);
                 return null;
             }
             PlaceAttribute.SSYPromotionTypeSelectedValue='';
             PlaceAttribute.SSYOTCostTypeSelectedValue='';
             PlaceAttribute.CostSourceSelectedValue='';
             
             return null;
     }
     //删除竞品信息
      public PageReference DeleteCompetitionBrandAction()
      {
         for(Integer i=0;i<CompetitionBrandList.size();i++)
         {
              ActivityCompetitionBrandEntry entry=CompetitionBrandList[i];
             if(entry.IsCheck)
             {
                 CompetitionBrandList.remove(i);
                 delete [select id from Activity_Competition_Brand_Information__c where id=:entry.ActivityCompetitionMsg.Id];
                 i--;
             }
         }
          return null;
      }
      //保存第1步
      public PageReference SaveAllSetp1Activity()
      {
          try
          {
              if(ActivityInit.Activity_Start_Date__c==NULL || ActivityInit.Activity_Start_Date__c<system.today())
                  throw new CustomException('活动开始时间不能为空，且不能小于今天');
              if(ActivityInit.Activity_End_Date__c==NULL)
                  throw new CustomException('活动结束时间不能为空');
               if(ActivityInit.Name==NULL)
                  throw new CustomException('活动名字不能为空');
              if(ActivityInit.Activity_Start_Date__c>ActivityInit.Activity_End_Date__c)
                  throw new CustomException('活动开始时间不能大于活动结束时间');
              if(ActivityInit.KAMFinishAdjustDate__c==NULL || ActivityInit.KAMFinishAdjustDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('KAM完成调整时间不能为空，且必须在活动开始的前三周');
               if(ActivityInit.SRTMFinishDate__c==NULL || ActivityInit.SRTMFinishDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('SRTM完成调整时间不能为空，且必须在活动开始的前三周');
               if(ActivityInit.ASMFinishDate__c==NULL || ActivityInit.ASMFinishDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('ASM完成调整时间不能为空，且必须在活动开始的前三周');
               if(ActivityInit.NTMKTFinishApproveDate__c==NULL  ||  ActivityInit.NTMKTFinishApproveDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('NTMKT完成审批时间不能为空，且必须在活动开始的前三周');
               if(ActivityInit.RSMFinishApproveDate__c==NULL ||  ActivityInit.RSMFinishApproveDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('RSM完成审批时间不能为空，且必须在活动开始的前三周');
               if(ActivityInit.RTMFinishApproveDate__c==NULL || ActivityInit.RTMFinishApproveDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('RTM完成审批时间不能为空，且必须在活动开始的前三周');
               if(ActivityInit.SRTMFinishApproveDate__c==NULL ||  ActivityInit.SRTMFinishApproveDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('SRTM完成审批时间不能为空，且必须在活动开始的前三周');
               if(ActivityInit.ASMConfirmDate__c==NULL || ActivityInit.ASMConfirmDate__c>ActivityInit.Activity_Start_Date__c.addDays(-21))
                  throw new CustomException('ASM确认活动时间不能为空，且必须在活动开始的前三周');
           }
           catch(Exception ex)
           {
                ApexPages.addMessages(ex);
                 return null;
           }
              
          //如果是己提交状态直接跳至第二步
           if(RecordId!=NULL && (ActivityInit.Activity_Stage__c=='总部已发起活动' || ActivityInit.Activity_Stage__c=='总部已发起活动'))
           {
               pageReference pr = new pageReference('/apex/NTMKTStep2AddParticipator?id='+ActivityInit.id);     
                pr.setredirect(true);   
                return pr;
           }
           
          if(RecordId!=NULL)//更新状态)
          {
              delete [select id from Resource_Allocation__c where Activity_Information_Name__c=:RecordId]; 
              delete [select id from Resource_Allocation_Detail__c where ActivityId__c=:RecordId];
          }
          SaveAndSubmit();
           pageReference pr = new pageReference('/apex/NTMKTStep2AddParticipator?id='+ActivityInit.id);     
            pr.setredirect(true);   
            return pr;
      }
      //保存第2步
      public PageReference SaveAllSetp2Activity()
      {
          try
          {
              if(CompetitionBrandList==NULL || CompetitionBrandList.size()==0)
                  throw new CustomException('请填写竞品信息');
             if(ParticipatorAreaEntryList==NULL || ParticipatorAreaEntryList.size()==0)
                  throw new CustomException('请填写OT参与者信息');
             if(ParticipatorAreaKAList==NULL || ParticipatorAreaKAList.size()==0)
                 throw new CustomException('请填写KA参与者信息');
             
                if(RecordId!=NULL && (ActivityInit.Activity_Stage__c=='总部已发起活动' || ActivityInit.Activity_Stage__c=='总部已发起活动'))
                {
                      pageReference pr = new pageReference('/apex/NTMKTAdjustKAResource?id='+ActivityInit.id);     
                      pr.setredirect(true);   
                      return pr;
                }
                
                // List<Participator_Detail_Outlet__c> otParList=new List<Participator_Detail_Outlet__c>();
                 Map<String,Activity_Target_And_Allocation_Total__c> TargetAllocationTotal=new  Map<String,Activity_Target_And_Allocation_Total__c>();
                 map<Id,Participator_Detail_Outlet__c> ALLidList=new map<Id,Participator_Detail_Outlet__c>();
                 set<string> KaList=new set<string>();//存KA名称列表
                 set<string> KaCityList=new set<string>();//存KA城市列表
                 set<string> otList=new set<string>();//存OT城市列表
               for(Participator_Detail_Outlet__c DetailOutlet:[select Id,TargetNumber__c,Outlet_Name__c,KA__c,City__c,SubRegion__c,Region__c,Area__c,OutletResourceType__c 
                                                                                from Participator_Detail_Outlet__c 
                                                                                where Participator_Area__r.Activity_Name__c=:RecordId])
               {
                   ALLidList.put(DetailOutlet.Outlet_Name__c,DetailOutlet);//所有的门店ID
                
                   // if(DetailOutlet.OutletResourceType__c=='OT')//获取OT的参与列表，用来生成竞品信息
                   //      otParList.add(DetailOutlet);
                   //By KA
                     if(DetailOutlet.KA__c!=NULL)
                     {
                         if(!TargetAllocationTotal.containsKey(DetailOutlet.KA__c))
                         {
                              Activity_Target_And_Allocation_Total__c KAataat=new Activity_Target_And_Allocation_Total__c();
                              KAataat.Activity_Information__c=ActivityInit.id;
                              KAataat.KAName__c=DetailOutlet.KA__c;                             
                              KAataat.TargetNumber__c=0;
                              KAataat.Type__c='KA';
                              TargetAllocationTotal.put(DetailOutlet.KA__c,KAataat);
                          }
                          //By KA and City
                       if(!TargetAllocationTotal.containsKey(DetailOutlet.KA__c+DetailOutlet.City__c))
                       {
                            Activity_Target_And_Allocation_Total__c kaCityataat=new Activity_Target_And_Allocation_Total__c();
                            kaCityataat.Activity_Information__c=ActivityInit.id;
                            kaCityataat.CityName__c=DetailOutlet.City__c;
                            kaCityataat.KAName__c=DetailOutlet.KA__c;
                            kaCityataat.TargetNumber__c=0;
                            kaCityataat.Type__c='KACity';
                            kaCityataat.SubRegion__c=DetailOutlet.SubRegion__c;
                            kaCityataat.Region__c=DetailOutlet.Region__c;
                            kaCityataat.Area__c=DetailOutlet.Area__c;
                            kaCityataat.OutletNumber__c=1;
                            TargetAllocationTotal.put(DetailOutlet.KA__c+DetailOutlet.City__c,kaCityataat);
                        }
                        else
                        {
                            Activity_Target_And_Allocation_Total__c kaCityataat=TargetAllocationTotal.get(DetailOutlet.KA__c+DetailOutlet.City__c);
                            kaCityataat.OutletNumber__c+=1;
                            TargetAllocationTotal.put(DetailOutlet.KA__c+DetailOutlet.City__c,kaCityataat);
                        }
                     }
                     else
                     {
                         if(!TargetAllocationTotal.containsKey('OT'+DetailOutlet.City__c))
                         {
                              Activity_Target_And_Allocation_Total__c OTataat=new Activity_Target_And_Allocation_Total__c();
                             OTataat.Activity_Information__c=ActivityInit.id;
                             OTataat.CityName__c=DetailOutlet.City__c;
                             OTataat.TargetNumber__c=0;
                             OTataat.Type__c='OTCity';
                             OTataat.SubRegion__c=DetailOutlet.SubRegion__c;
                             OTataat.Region__c=DetailOutlet.Region__c;
                             OTataat.Area__c=DetailOutlet.Area__c;
                             OTataat.OutletNumber__c=1;
                             TargetAllocationTotal.put('OT'+DetailOutlet.City__c,OTataat);
                         }
                         else
                         {
                              Activity_Target_And_Allocation_Total__c OTataat=TargetAllocationTotal.get('OT'+DetailOutlet.City__c);
                             OTataat.OutletNumber__c+=1;
                             TargetAllocationTotal.put('OT'+DetailOutlet.City__c,OTataat);
                         }
                     }
               }
            //   decimal KATotalTarget=0,OTTotalTarget=0;//保存KA和OT的target值 
               
                 Map<Id,Decimal> OutletTargetList=new Map<Id,Decimal>();
                  for(Activity_Target_For_Outlet__c tar:[select Outlet__c,Outlet__r.CityName__c,Target_Sum__c,KA_Chain_Customers__c,OutletArea__c from Activity_Target_For_Outlet__c where Outlet__c in: ALLidList.Keyset()])
                  {
                      if(ALLidList.containsKey(tar.Outlet__c))
                      {
                          Participator_Detail_Outlet__c pdo=ALLidList.get(tar.Outlet__c);
                          pdo.TargetNumber__c=tar.Target_Sum__c;
                          ALLidList.put(tar.Outlet__c,pdo);
                      }
                   
                      //KA
                      if(tar.KA_Chain_Customers__c!=NULL)
                      {
                            if(TargetAllocationTotal.containsKey(tar.KA_Chain_Customers__c))//按KA汇总
                           {
                               Activity_Target_And_Allocation_Total__c ataat=TargetAllocationTotal.get(tar.KA_Chain_Customers__c);   
                               ataat.TargetNumber__c+=tar.Target_Sum__c;
                               TargetAllocationTotal.put(tar.KA_Chain_Customers__c,ataat);
                            }
                            //累加KA的target的值, total by city
                            if(TargetAllocationTotal.containsKey(tar.KA_Chain_Customers__c+tar.Outlet__r.CityName__c))
                            {
                                   Activity_Target_And_Allocation_Total__c ataat=TargetAllocationTotal.get(tar.KA_Chain_Customers__c+tar.Outlet__r.CityName__c);
                                   ataat.TargetNumber__c+=tar.Target_Sum__c;
                                   TargetAllocationTotal.put(tar.KA_Chain_Customers__c+tar.Outlet__r.CityName__c,ataat);
                             }
                           
                       }
                       else
                       {
                           //累加OT的target的值, total by city
                            if(TargetAllocationTotal.containsKey('OT'+tar.Outlet__r.CityName__c))
                            {
                                       Activity_Target_And_Allocation_Total__c ataat=TargetAllocationTotal.get('OT'+tar.Outlet__r.CityName__c);
                                       ataat.TargetNumber__c+=tar.Target_Sum__c;
                                       TargetAllocationTotal.put('OT'+tar.Outlet__r.CityName__c,ataat);
                             }
                       }
                  }
                  
                  update ALLidList.values();//更新门店target
                  delete [select id from Activity_Target_And_Allocation_Total__c  where Activity_Information__c=:ActivityInit.id];
                  insert TargetAllocationTotal.values();
                  
                  //删除参与者Area为零的数据
                 delete  [select id from ParticipatorArea__c where Outlet_Sum_Total__c=0 and Activity_Name__c=:ActivityInit.id];
               //更新活动
                update ActivityInit;
           }
           catch(Exception ex)
           {
                 ApexPages.addMessages(ex);
                 return null;
           }
            pageReference pr = new pageReference('/apex/NTMKTAdjustKAResource?id='+ActivityInit.id);     
            pr.setredirect(true);   
            return pr;
      }
     // 提交
      public PageReference SubmitAllActivity()
      {
          ActivityInit.Activity_Stage__c='总部已发起活动';
          SaveAndSubmit();
          return null;
      }
      //保存数据
      public Boolean SaveAndSubmit()
      {
           List<Resource_Allocation__c> resourceList=new  List<Resource_Allocation__c>();
          List<Activity_Competition_Brand_Information__c> competitionList=new  List<Activity_Competition_Brand_Information__c>();
          List<ParticipatorArea__c> participatorList=new  List<ParticipatorArea__c>();
          if(participatorDetailArea==NULL)
               participatorDetailArea=new  List<Participator_Detail_Area__c>();
          Set<String> AreaString=new Set<String>();
          List<Resource_Allocation_Detail__c> reourceOTOutletDetail=new List<Resource_Allocation_Detail__c>();
          List<Resource_Allocation_Detail__c> reourceKAOutletDetail=new List<Resource_Allocation_Detail__c>();
     
              if(ActivityInit.id!=NULL)
              {
                  update ActivityInit;
              }
              else
              {
                  //保存活动基本信息
                  insert ActivityInit;
              }
              //保存资源
              if(ResourceEntryList!=NULL)
              {
                  for(ActivityResourceEntry entry:ResourceEntryList)
                  {
                      entry.Res.Activity_Information_Name__c=ActivityInit.id;
                      entry.Res.Resource_Type__c='ET';
                      resourceList.add(entry.Res);
                  }
                   insert resourceList;
              }
            return true;
        }
        
        public PageReference ParticipatorOnCheckAction()
        {
            try
            {
             if(ActivityInit.Activity_Stage__c=='草稿')
             {   
                if(getTypeKAOrOT=='KA')
                {
                    delete [select id from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:ActivityInit.id and Participator_Area__r.Type__c='KA'];
                    delete [select id from ParticipatorArea__c where Activity_Name__c=:ActivityInit.id and Type__c='KA'];
                    mapParticipatorAreaKAList.clear();
                    ParticipatorAreaKAList.clear();
                }
                else if(getTypeKAOrOT=='OT')
                {
                     delete [select id from Participator_Detail_Outlet__c where Participator_Area__r.Activity_Name__c=:ActivityInit.id and Participator_Area__r.Type__c='OT'];
                    delete [select id from ParticipatorArea__c where Activity_Name__c=:ActivityInit.id and Type__c='OT'];
                    mapParticipatorAreaList.clear();
                    ParticipatorAreaEntryList.clear();
                }
              }
            }
            catch(DMLException ex)
            {
              
                ApexPages.addMessages(new CustomException('由于数据量大，请分多次删除数据'));
                 return null;
            }
            return null;
        }
        
        //上一步
        public PageReference PreviousStep()
        {
             pageReference pr = new pageReference('/apex/InitActivityForNTMKTList?id='+ActivityInit.id);     
            pr.setredirect(true);   
            return pr;
        }
        //取消活动
        public PageReference CancelActivity()
        {
             if(RecordId!=NULL)
             {
                     ActivityInit.Activity_Stage__c='活动已取消';
                     ActivityInit.Activity_Type_State__c='取消';
                     update ActivityInit;
             }
            pageReference pr = new pageReference('/'+ActivityInit.id);     
            pr.setredirect(true);   
            return pr;
        }
}